import { useState } from "react";
import { useHistory } from "react-router";

import Button from '../../components/Button';
import FormElem  from "../../components/FormElem";
import Header from "../../components/Header";
import Row from "../../components/Row";

import Side from '../common/Side';

import styles from './login.module.css';

const MailRegex = new RegExp(/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/);

const Login = () => {

  const history = useHistory();

  const [mail, setMail] = useState();
  const [pass, setPass] = useState();
  const [fail, setFail] = useState({});

  const updateMail = (e) => {
    const mailString = e.target.value;
    setMail(mailString);

    if (mailString.match(MailRegex)) {
      setFail({...fail, mail: undefined});
    } else {
      setFail({...fail, mail: {stat: 'dead', msg:'邮箱格式不太对，请检查一下'}});
    }
  }

  const updatePass = (e) => {
    setPass(e.target.value);
  }

  const submit = async () => {
    
    const response = await fetch('/auth/log', {
      method: 'POST',
      headers: {
        "Content-type": "application/json;charset=UTF-8",
      },
      body: JSON.stringify({mail, pass}),
    });

    const {ok, code, user, role} = await response.json();
    
    if (!ok) {
      const msg = {
        'LOG.MISMATCH': '用户名（邮箱）和密码不匹配'
      }[code]

      setFail({...fail, pass:{stat: 'dead', msg}});

    } else {

      Object.assign(sessionStorage, {user, role});
      history.push('/dashboard');
    }
  }

  const toReg = () => {
    history.push('/reg');
  }

  return <div className={styles['page']}>
    <Side />
    <div style={{margin: 10}}>
      <Header text='Login' />
      <FormElem type='text' label='Email' value={mail} {...fail.mail} onChange={updateMail}/>
      <FormElem type='password' label='Password' value={pass} {...fail.pass} onChange={updatePass}/>
      <Row>
        <Button onClick={submit}> Login </Button>
        <Button color='base03' isOutlined onClick={toReg}> to Register </Button>
      </Row>
    </div>
  </div>
}


export default Login;